//
//  TGChooseVideoView.m
//  TongGuanLease
//
//  Created by 张奇 on 2022/8/29.
//

#import "TGChooseVideoView.h"
#import "TGChoosePhotoCell.h"
#import "ZFImagePicker.h"
#import "TGUploadVideoTool.h"
#import "MBProgressHUD+RY.h"
#import "TGUrlInfoModel.h"
#import "LBXPermissionSetting.h"
#import "LBXPermission.h"
#import "ResetSizeImage.h"
#import "CLPlayerView.h"
#import "ZLCustomCamera.h"
#import "ZLPhotoManager.h"

@interface TGChooseVideoView ()<UICollectionViewDataSource, UICollectionViewDelegate, TGChoosePhotoCellDelegate>
@property (strong, nonatomic) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *videoUrlInfoArray, *videoAssetsArray;
@property (nonatomic, strong) NSArray *filPathArray;

@property (nonatomic, strong) TGUploadVideoTool *uploadTool;
@property (nonatomic, strong) CLPlayerView *playerView;

@end

@implementation TGChooseVideoView

- (void)awakeFromNib {
    [super awakeFromNib];
    self.backgroundColor = UIColorForBackground;
    if (self.maxCount == 0) {
        self.maxCount = 100;
    }
    [self setupUI];
}

- (instancetype)initWithMaxCount:(NSInteger)maxCount
                 uploadImageType:(UploadImageType)uploadImageType
                        delegate:(id<TGChooseVideoViewDelegate>)delegate {
    if (self = [super init] ) {
        self.backgroundColor = UIColorForBackground;
        self.maxCount = (maxCount==0? 100:maxCount);
        self.delegate = delegate;
        self.uploadVideoType = uploadImageType;
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    self.filPathArray = @[@"USER_SERVICE", @"EQUIPMENT_SERVICE", @"SETTLEMENT_SERVICE", @"CRM_SERVICE", @"CONTRACT_SERVICE", @"ASSETS_SERVICE", @"SYSTEM_SERVICE", @"WORK_ORDER_SERVICE", @"NCC_AGGREGATION_SERVICE", @"WORKFLOW_SERVICE", @"THIRD_PARTY_SERVICE", @"RULE_ENGINE_SERVICE", @"SCHEDULE_SERVICE", @"ANALYSIS_SERVICE"];
    
    UIView *contentView = [[UIView alloc] init];
    [self addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    [contentView addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    [self.collectionView reloadData];
}

- (void)setSelectVideoUrlInfoArray:(NSArray<TGUrlInfoModel *> *)selectVideoUrlInfoArray {
    _selectVideoUrlInfoArray = selectVideoUrlInfoArray;
    self.videoUrlInfoArray = [NSMutableArray arrayWithArray:selectVideoUrlInfoArray];
    
    [self.collectionView reloadData];
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.maxCount >0 && self.videoUrlInfoArray.count >= self.maxCount) {
        return self.videoUrlInfoArray.count;
    } else {
        return self.videoUrlInfoArray.count+1;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TGChoosePhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TGChoosePhotoCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.row = indexPath.item;
    if (indexPath.row == self.videoUrlInfoArray.count) {
        [cell.photoBtn setImage:[UIImage imageNamed:@"workBtnch_addPic"] forState:UIControlStateNormal];
        cell.delectBtn.hidden = YES;
        cell.playImageView.hidden = YES;
    } else {
        
        TGUrlInfoModel *urlInfoModel = self.videoUrlInfoArray[indexPath.row];
        NSURL *url = [NSURL URLWithString:urlInfoModel.fullPath];
        UIImage *image = [ResetSizeImage getVideoThumbnailWithUrl:url];
        if (image == nil) {
            [cell.photoBtn setImage:kImage(@"common_placehoder") forState:UIControlStateNormal];
        } else {
            [cell.photoBtn setImage:image forState:UIControlStateNormal];
        }
        
        cell.delectBtn.hidden = NO;
        cell.playImageView.hidden = NO;
    }
    return cell;
}
#pragma mark -
-(void)btnClick:(NSInteger)section Index:(NSInteger)row {
    if (row == self.videoUrlInfoArray.count) {
        //添加视频
        if (self.videoUrlInfoArray.count>=self.maxCount) {
            return;
        }
        [self beginChooseVideo];
    } else {
        //查看视频
        NSMutableArray *tem = [NSMutableArray array];
        for (TGUrlInfoModel *urlInfoModel in self.videoUrlInfoArray) {
            [tem addObject:GetDictForPreviewPhoto([NSURL URLWithString:R(urlInfoModel.fullPath)], ZLPreviewPhotoTypeURLVideo)];
        }
        
        [[TGGlobalSharedInstance photoActionSheet:self.getCurrentVC] previewPhotos:tem index:row hideToolBar:YES complete:^(NSArray * _Nonnull photos) {
            NSLog(@"%@", photos);
        }];
        
    }
}

-(void)deleteBtnClick:(NSInteger)section Index:(NSInteger)row {
    if (self.videoAssetsArray.count > 0 && row <= (self.videoAssetsArray.count-1)) {
        [self.videoAssetsArray removeObjectAtIndex:row];
    }
    [self.videoUrlInfoArray removeObjectAtIndex:row];
    [self.collectionView reloadData];
    if ([self.delegate respondsToSelector:@selector(tgChooseVideoViewDidSelectvideoUrlInfoArray:)]) {
        [self.delegate tgChooseVideoViewDidSelectvideoUrlInfoArray:self.videoUrlInfoArray];
    }
}


- (void)beginChooseVideo {
    
//    [LEEAlert actionsheet].config
//        .LeeActionSheetBottomMargin(0)
//        .LeeStatusBarStyle(UIStatusBarStyleLightContent)
//        .LeeAddAction(^(LEEAction * _Nonnull action) {
//            action.title = @"录制上传";
//            action.titleColor = RGBA(51, 51, 51, 1);
//            action.font = TGAutoFont(18);
//            action.clickBlock = ^{
//                [self takeVideo];
//            };
//        }).LeeAddAction(^(LEEAction * _Nonnull action) {
//            action.title = @"本地上传";
//            action.titleColor = RGBA(51, 51, 51, 1);
//            action.font = TGAutoFont(18);
//            action.clickBlock = ^{
//                [self localVideo];
//            };
//        }).LeeAddAction(^(LEEAction * _Nonnull action) {
//            action.title = @"取消";
//            action.type = LEEActionTypeCancel;
//            action.titleColor = RedColor;
//            action.font = TGAutoFont(18);
//            action.clickBlock = ^{
//            };
//        }).
//    LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type, CGSize size)  {
//        return CGRectGetWidth([[UIScreen mainScreen] bounds]);
//    }).LeeShow();
    
    [self localVideo];
}

- (void)takeVideo {
    
    [LBXPermission authorizeWithType:LBXPermissionType_Photos completion:^(BOOL granted, BOOL firstTime) {
        if (granted) {
            
            ZLCustomCamera *camera = [[ZLCustomCamera alloc] init];
            camera.allowTakePhoto = YES;
            camera.allowRecordVideo = YES;
//            camera.sessionPreset = ZLCaptureSessionPreset1280x720;
//            camera.circleProgressColor = configuration.cameraProgressColor;
            camera.maxRecordDuration = 120;
            @zl_weakify(self);
            camera.doneBlock = ^(UIImage *image, NSURL *videoUrl) {
                
                [ZLPhotoManager saveVideoToAblum:videoUrl completion:^(BOOL suc, PHAsset *asset) {
                    @zl_strongify(self);
                    if (suc) {
                        
                        [TGGCD executeMainOpeation:^{
                            
                            NSMutableArray *resultImages = [NSMutableArray array];
                            
                            [self updateVideoAssets:@[asset] finish:^(NSArray <TGUrlInfoModel *>*imageInfoArray) {
                                for (int i = 0; i<resultImages.count; i++) {
                                    if (self.videoUrlInfoArray.count < self.maxCount) {
                                        //小于最大数量，可添加，否则忽略
                                        [self.videoUrlInfoArray addObject:imageInfoArray[i]];
                                    }
                                }
                                [self.videoUrlInfoArray addObjectsFromArray:imageInfoArray];
                                [self.collectionView reloadData];
                                if ([self.delegate respondsToSelector:@selector(tgChooseVideoViewDidSelectvideoUrlInfoArray:)]) {
                                    [self.delegate tgChooseVideoViewDidSelectvideoUrlInfoArray:self.videoUrlInfoArray];
                                }
                            }];
                            
                            
                        }];
                        
                        
                    }
                    
                }];
            };
            [self.getCurrentVC showDetailViewController:camera sender:nil];
            
        } else if(!firstTime) {
            [LBXPermissionSetting showAlertToDislayPrivacySettingWithTitle:@"提示" msg:@"您好，需要使用相机来进行上传视频功能，是否前往打开权限" cancel:@"暂不打开" setting:@"设置" ];
        }
        
    }];
    
}

- (void)localVideo {
    
    [LBXPermission authorizeWithType:LBXPermissionType_Photos completion:^(BOOL granted, BOOL firstTime) {
        if (granted) {
            
            ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
            actionSheet.sender = self.getCurrentVC;
//            actionSheet.configuration.sessionPreset = ZLCaptureSessionPreset1920x1080;
            actionSheet.configuration.showCaptureImageOnTakePhotoBtn = NO;
            actionSheet.configuration.maxSelectCount = self.maxCount;
            actionSheet.configuration.allowSelectImage = NO;
            actionSheet.configuration.allowSelectVideo = YES;
            actionSheet.configuration.allowRecordVideo = YES;
            actionSheet.configuration.maxVideoDuration = 1200;
            actionSheet.configuration.maxRecordDuration = 120;
//            actionSheet.configuration.mutuallyExclusiveSelectInMix = YES;
            actionSheet.configuration.statusBarStyle = UIStatusBarStyleDefault;
            actionSheet.configuration.navTitleColor = RGB(44, 45, 46);
            actionSheet.configuration.navBarColor = UIColorWhite;
            if (self.videoAssetsArray.count > 0) {
                actionSheet.arrSelectedAssets = self.videoAssetsArray;
            }
            
            actionSheet.cancleBlock = ^{
                NSLog(@"取消选择视频");
            };
            [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
                NSLog(@"image:%@ ******  assets:%@", images, assets);
                
                
                [TGGCD executeMainOpeation:^{
                    
                    NSMutableArray *resultImages = [NSMutableArray array];
                    NSMutableArray *resultAssets = [NSMutableArray array];
                    //先去重
                    for (int i = 0; i < assets.count; i++) {
                        PHAsset *currtAsset = assets[i];
                        if (![self.videoAssetsArray containsObject:currtAsset]) {
                            [resultImages addObject:images[i]];
                            [resultAssets addObject:currtAsset];
                        }
                    }
                    
                    [self updateVideoAssets:resultAssets finish:^(NSArray <TGUrlInfoModel *>*imageInfoArray) {
//                        for (int i = 0; i<resultImages.count; i++) {
//                            if (self.videoUrlInfoArray.count < self.maxCount) {
//                                //小于最大数量，可添加，否则忽略
//                                [self.videoUrlInfoArray addObject:imageInfoArray[i]];
//                            }
//                        }
                        for (int i = 0; i<resultImages.count; i++) {
                            if (self.videoUrlInfoArray.count < self.maxCount) {
                                //小于最大数量，可添加，否则忽略
                                if (assets.count > 0) {
                                    [self.videoAssetsArray addObject:resultAssets[i]];
                                }
                                [self.videoUrlInfoArray addObject:imageInfoArray[i]];
                            }
                        }
                        
//                        [self.videoUrlInfoArray addObjectsFromArray:imageInfoArray];
                        [self.collectionView reloadData];
                        if ([self.delegate respondsToSelector:@selector(tgChooseVideoViewDidSelectvideoUrlInfoArray:)]) {
                            [self.delegate tgChooseVideoViewDidSelectvideoUrlInfoArray:self.videoUrlInfoArray];
                        }
                    }];
                    
                    
                }];
                
                
            }];
            [actionSheet showPhotoLibraryWithSender:self.getCurrentVC];
            
            
        } else if(!firstTime) {
            [LBXPermissionSetting showAlertToDislayPrivacySettingWithTitle:@"提示" msg:@"您好，需要使用相机来进行上传视频功能，是否前往打开权限" cancel:@"暂不打开" setting:@"设置" ];
        }
        
    }];
    
}

- (void)updateVideoAssets:(NSArray <PHAsset *> *)videos finish:(ComplentValueBlock)finish {
    
    MBProgressHUD *hud = [MBProgressHUD showMessage:@"上传中..." toView:self.getCurrentVC.view];
    NSString *uploadImageTypeStr = self.filPathArray[self.uploadVideoType];
    if (EmptyCheck(uploadImageTypeStr)) {
        [TGProgressHUD showHUDTip:@"请完善上传类型"];
    }
    
    [self.uploadTool uploadVideoWithFilePath:uploadImageTypeStr videoArray:videos complemention:^(NSString * _Nonnull progressStr, NSError * _Nullable error, BOOL isFinished, NSArray<TGUrlInfoModel *> * _Nullable imageInfoArray) {
        NSLog(@"-main---%@-----%d", progressStr, isFinished);
        if (error) {
            [TGGCD executeMainOpeation:^{
//                hud.label.text = @"保存失败";
                [hud hideAnimated:YES];
            }];
            return;
        }
        [TGGCD executeMainOpeation:^{
            hud.label.text = [NSString stringWithFormat:@"上传中 %@", progressStr];
        }];
        if (isFinished) {
            [TGGCD executeMainOpeation:^{
                [hud hideAnimated:YES];
            }];
            //上传结束，开始回调
            if (finish) {
                finish(imageInfoArray);
            }
        }
    }];
    
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat width = SCREEN_WIDTH-TableViewSpace*2;
        CGFloat itemWH = ceil((width-TableViewSpace*3.0)/4.0);
        
        flowLayout.itemSize = CGSizeMake(itemWH, itemWH);
        flowLayout.minimumLineSpacing = TableViewSpace;
        flowLayout.minimumInteritemSpacing = RatioWidth(10);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [_collectionView registerNib:[UINib nibWithNibName:@"TGChoosePhotoCell" bundle:nil] forCellWithReuseIdentifier:@"TGChoosePhotoCell"];
        _collectionView.backgroundColor = UIColorWhite;
        _collectionView.alwaysBounceHorizontal = NO;
        _collectionView.scrollEnabled = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
    }
    return _collectionView;
}

- (NSMutableArray *)videoUrlInfoArray {
    if (!_videoUrlInfoArray) {
        _videoUrlInfoArray = [NSMutableArray array];
    }
    return _videoUrlInfoArray;
}

- (NSMutableArray *)videoAssetsArray {
    if (!_videoAssetsArray) {
        _videoAssetsArray = [NSMutableArray array];
    }
    return _videoAssetsArray;
}

- (TGUploadVideoTool *)uploadTool {
    if (!_uploadTool) {
        _uploadTool = [[TGUploadVideoTool alloc] init];
    }
    return _uploadTool;
}


@end
